import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import '../models/user.dart';
import 'package:oramemo/common/langs/text_key.dart';

class UserEditDialog extends StatefulWidget {
  final User? user; // If null, it indicates add mode

  const UserEditDialog({Key? key, this.user}) : super(key: key);

  @override
  State<UserEditDialog> createState() => _UserEditDialogState();
}

class _UserEditDialogState extends State<UserEditDialog> {
  late final TextEditingController _nameController;
  late final TextEditingController _phoneController;

  @override
  void initState() {
    super.initState();
    _nameController = TextEditingController(text: widget.user?.name);
    _phoneController = TextEditingController(text: widget.user?.phone);
  }

  bool _isValidPhone(String phone) => phone.length > 5;

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: Text(widget.user == null 
          ? TextKey.userEditDialogTitleAdd.tr 
          : TextKey.userEditDialogTitleEdit.tr),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          _buildTextField(
            controller: _nameController,
            label: TextKey.userEditDialogNameLabel.tr,
            hint: TextKey.userEditDialogNameHint.tr,
          ),
          const SizedBox(height: 16),
          _buildTextField(
            controller: _phoneController,
            label: TextKey.userEditDialogPhoneLabel.tr,
            hint: TextKey.userEditDialogPhoneHint.tr,
            isPhone: true,
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () => Get.back(),
          child: Text(TextKey.userEditDialogCancel.tr),
        ),
        TextButton(
          onPressed: _onConfirm,
          child: Text(TextKey.userEditDialogConfirm.tr),
        ),
      ],
    );
  }

  Widget _buildTextField({
    required TextEditingController controller,
    required String label,
    required String hint,
    bool isPhone = false,
  }) {
    return TextField(
      controller: controller,
      keyboardType: isPhone ? TextInputType.phone : TextInputType.text,
      maxLength: 64,
      inputFormatters: isPhone ? [FilteringTextInputFormatter.digitsOnly] : [],
      decoration: InputDecoration(
        labelText: label,
        hintText: hint,
        counterText: '',
      ),
    );
  }

  void _onConfirm() {
    final name = _nameController.text.trim();
    final phone = _phoneController.text.trim();

    if (name.isEmpty) {
      Get.snackbar(TextKey.userEditDialogErrorEmptyName.tr, '');
      return;
    }

    if (!_isValidPhone(phone)) {
      Get.snackbar(TextKey.userEditDialogErrorInvalidPhone.tr, '');
      return;
    }

    final String defaultRoleStr = TextKey.userEditDialogDefaultRole.tr;
    final user = User(
      id: widget.user?.id ?? '',
      userId: widget.user?.userId ?? '',
      name: name,
      phone: phone,
      role: widget.user?.role ?? defaultRoleStr,
      avatarUrl: widget.user?.avatarUrl ?? '',
    );
    Get.back(result: user);
  }

  @override
  void dispose() {
    _nameController.dispose();
    _phoneController.dispose();
    super.dispose();
  }
} 